package app.fugema.shop.main.home.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;

import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.ada.BaseRVAdapter;
import com.base.common.view.adapter.ada.SingleUniversalAdapter;
import com.base.common.view.adapter.connector.BaseItemMultiType;
import com.base.common.view.base.BaseTitleActivity;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.param.SearchParam;
import com.tencent.lbssearch.object.result.SearchResultObject;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;

import java.util.ArrayList;
import java.util.List;

import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.ActivityLocationCityBinding;
import app.fugema.shop.main.home.model.LocaCityBean;
import app.fugema.shop.main.home.model.PoiPlaceBean;
import app.fugema.shop.main.online.vm.OnlineVM;
import app.fugema.shop.main.setting.model.CustomRegionBean;
import app.fugema.shop.util.CityDataUtil;
import app.fugema.shop.util.SimpleTextWatcher;

public class LocationCityActivity extends BaseTitleActivity<ActivityLocationCityBinding, OnlineVM> {


    public static void start(Context context , LocaCityBean cityBean)
    {
        Intent intent = new Intent(context, LocationCityActivity.class);
        intent.putExtra("currentCity", JacksonUtils.transBean2Json( cityBean ));
        context.startActivity(intent);
    }

    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_city);
    }

    private SingleUniversalAdapter<PoiPlaceBean> adapter;

    private LocaCityBean mCityBean;

    private TencentLocationManager tlLocationMgr;

    private TencentSearch tencentSearch;

    // 省市区 3 级联动
    private OptionsPickerView pickerView;

    private List<CustomRegionBean> province1Item = new ArrayList<>();
    private ArrayList<ArrayList<CustomRegionBean>> city2Item = new ArrayList<>();

    @Override
    protected void initView()
    {
        super.initView();
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("定位",R.color.white);

        adapter = new SingleUniversalAdapter<PoiPlaceBean>() {
            @Override
            public int getLayoutId()
            {
                return R.layout.item_location_city_view;
            }

            @Override
            public void onItemClick(View view, BaseRVAdapter adapter, int onclickType, int position, PoiPlaceBean bean)
            {
                super.onItemClick(view, adapter, onclickType, position, bean);
                //UIUtils.showToastSafes( bean.getTitle() );
                mCityBean.setLongitude( bean.getLng() );
                mCityBean.setLatitude( bean.getLat() );
                mCityBean.setCityName( bean.getTitle() );

                LiveEventBus.get(AppConstants.EventKey.CITY_SELECT).post( mCityBean );
                finish();
            }
        };
        binding.rvRecyclerView.setAdapter(adapter);

        viewUtils.setStateLayout(binding.rvRecyclerView, this);

        binding.ivLocation.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                UIUtils.showToastSafes("正在重新定位");
                singleGetLocation();
            }
        });

        binding.etSearch.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(String content)
            {
                if( UIUtils.isNotEmpty( content ) )
                {
                    txSearchPoi(content);
                }
                else
                {
                    //清空搜索结果
                    adapter.clear();
                }
            }
        });

        //选择城市
        binding.rlLocationLayout.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view)
            {
                //显示省市区
                pickerView.show();
            }
        });

        tlLocationMgr = TencentLocationManager.getInstance(getActivity());
        //地址关键词搜索
        tencentSearch = new TencentSearch(this);

        pickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v)
            {
                StringBuffer citySb = new StringBuffer();
                String opt1tx_province = province1Item.size() > 0 ?
                        province1Item.get(options1).getName(): "";
                citySb.append( opt1tx_province );

                String opt2tx_city = city2Item.size() > 0
                        && city2Item.get(options1).size() > 0 ?
                        city2Item.get(options1).get(options2).getName() : "";
                citySb.append( opt2tx_city );

                binding.tvLocationName.setText( opt2tx_city );
                // 重新设置
                mCityBean.setCityName( opt2tx_city );
                mCityBean.setLatitude(0);
                mCityBean.setLongitude(0);
                adapter.clear();
            }
        }).setTitleText("请选择")
          .setDividerColor(Color.GRAY)
          .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
          .setContentTextSize(12)
          .build();
        province1Item = CityDataUtil.getInstance().getProvince1Items();
        city2Item = CityDataUtil.getInstance().getCity2Items();
        //2级选择器 省市
        pickerView.setPicker(province1Item, city2Item);

        //点击当前 位置  发送位置信息 结束页面
        binding.tvLocationDetail.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view)
            {

                if( mCityBean.getLatitude() == 0 || mCityBean.getLongitude() == 0  )
                {
                    UIUtils.showToastSafes( "请选择地区" );
                    return;
                }
                LiveEventBus.get(AppConstants.EventKey.CITY_SELECT , LocaCityBean.class)
                            .post( mCityBean );
                finish();
            }
        });

    }

    @Override
    protected void initData(Intent intent)
    {
        mCityBean =  JacksonUtils.getJsonBean( intent.getStringExtra("currentCity"),LocaCityBean.class);

        if(UIUtils.isNotEmpty( mCityBean ))
        {
           binding.tvLocationName.setText( mCityBean.getCityName() );

           binding.tvLocationDetail.setText( mCityBean.getCityName() );
        }

    }

    private void txSearchPoi(String keyWord)
    {

        //城市搜索  //设置搜索城市
        SearchParam.Region region = new SearchParam.Region(mCityBean.getCityName());
                //设置搜索范围不扩大
        region.autoExtend(false);

        //构建地点检索
        SearchParam searchParam = new SearchParam(keyWord, region);
        tencentSearch.search(searchParam, new HttpResponseListener<BaseObject>() {

            @Override
            public void onFailure(int arg0, String arg2,Throwable arg3)
            {
                UIUtils.showToastSafes( arg2 );
            }

            @Override
            public void onSuccess(int arg0, BaseObject arg1)
            {
                if (arg1 == null)
                {
                    return;
                }
                SearchResultObject obj = (SearchResultObject) arg1;
                if(obj.data == null)
                {
                    return;
                }
                List<PoiPlaceBean> poiList = new ArrayList<>();
                //将其他检索到的地点在地图上用 marker 标出来
                for(SearchResultObject.SearchResultData data : obj.data)
                {
                    LogUtil.e("SearchDemo","title:"+data.title + ";" + data.address);
                    PoiPlaceBean poi =new PoiPlaceBean();
                    poi.setTitle( data.title );
                    poi.setAddress( data.address );
                    poi.setLat( data.latLng.getLatitude() );
                    poi.setLng( data.latLng.getLongitude() );
                    poiList.add( poi );
                }
                adapter.clear();
                adapter.setDataList( poiList );

            }
        });

    }

    /**
     * 获取单次定位
     *
     */
    private void singleGetLocation()
    {
        tlLocationMgr.requestSingleFreshLocation(null, new TencentLocationListener() {
            @Override
            public void onLocationChanged(TencentLocation tencentLocation, int i, String s)
            {
                //LogUtil.e("tlLocationMgr","city = " + tencentLocation.getCity() + " District = " + tencentLocation.getDistrict() );
                //LogUtil.e( "s = " + JacksonUtils.transBean2Json( tencentLocation ));

                mCityBean.setCityName(tencentLocation.getCity());
                mCityBean.setItemType(BaseItemMultiType.TYPE_HEAD_ONE);
                mCityBean.setLatitude( tencentLocation.getLatitude() );
                mCityBean.setLongitude( tencentLocation.getLongitude() );

                binding.tvLocationName.setText( mCityBean.getCityName() );
                binding.tvLocationDetail.setText( mCityBean.getCityName() );
            }

            @Override
            public void onStatusUpdate(String s, int i, String s1)
            {
            }
        }, Looper.getMainLooper());
    }

}
